<template>
  <div class="pdf-preview-container">
    <div class="pdf-toolbar">
      <el-button-group>
        <el-button size="small" icon="el-icon-zoom-out" @click="zoomOut" title="缩小"></el-button>
        <el-button size="small" icon="el-icon-zoom-in" @click="zoomIn" title="放大"></el-button>
        <el-button size="small" @click="fitToPage" title="适应页面">
          <i class="el-icon-full-screen"></i>
        </el-button>
        <el-button size="small" icon="el-icon-refresh-left" @click="rotateLeft" title="向左旋转"></el-button>
        <el-button size="small" icon="el-icon-refresh-right" @click="rotateRight" title="向右旋转"></el-button>
      </el-button-group>

      <el-button-group>
        <el-button size="small" icon="el-icon-arrow-left" @click="prevPage" :disabled="currentPage <= 1"></el-button>
        <el-input
          size="small"
          v-model.number="currentPage"
          style="width: 50px"
          @change="goToPage"
        ></el-input>
        <span class="page-info">/ {{ numPages }}</span>
        <el-button size="small" icon="el-icon-arrow-right" @click="nextPage" :disabled="currentPage >= numPages"></el-button>
      </el-button-group>

      <el-button-group>
        <el-button size="small" icon="el-icon-download" @click="downloadPDF" title="下载"></el-button>
        <el-button size="small" icon="el-icon-printer" @click="printPDF" title="打印"></el-button>
      </el-button-group>
    </div>

    <div class="pdf-viewer" v-loading="loading">
      <pdf
        v-if="src"
        :src="src"
        :page="currentPage"
        :rotate="rotation"
        :scale="scale"
        @num-pages="numPages = $event"
        @page-loaded="pageLoaded"
        @loaded="loaded"
        @error="error"
      ></pdf>
      <div v-else class="empty-preview">
        <i class="el-icon-document"></i>
        <p>请先加载PDF文档</p>
      </div>
    </div>
  </div>
</template>

<script>
import pdf from 'vue-pdf'

export default {
  name: 'PDFPreview',
  components: {
    pdf
  },
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      src: null, // pdf文件源
      currentPage: 1,
      numPages: 0,
      scale: 1.0,
      rotation: 0,
      loading: true,
      pdfData: null
    }
  },
  methods: {
    async loadPDF() {
      try {
        this.loading = true
        if (this.url) {
          // 如果是URL，直接使用
          if (this.url.startsWith('http') || this.url.startsWith('blob')) {
            this.src = { url: this.url }
          } else {
            // 如果是本地路径，需要加载文件
            const response = await fetch(this.url)
            const blob = await response.blob()
            this.src = { url: URL.createObjectURL(blob) }
          }
        }
      } catch (error) {
        console.error('PDF加载错误:', error)
        this.$message.error('PDF加载失败')
      }
    },

    // 页面加载完成
    pageLoaded() {
      this.loading = false
    },

    // PDF文档加载完成
    loaded() {
      this.$message.success('PDF加载成功')
    },

    // 加载错误处理
    error(err) {
      console.error('PDF加载错误:', err)
      this.$message.error('PDF加载失败')
      this.loading = false
    },

    // 缩放控制
    zoomIn() {
      if (this.scale < 3) {
        this.scale = parseFloat((this.scale + 0.1).toFixed(1))
      }
    },

    zoomOut() {
      if (this.scale > 0.5) {
        this.scale = parseFloat((this.scale - 0.1).toFixed(1))
      }
    },

    fitToPage() {
      this.scale = 1.0
      this.rotation = 0
    },

    // 旋转控制
    rotateLeft() {
      this.rotation = (this.rotation - 90) % 360
    },

    rotateRight() {
      this.rotation = (this.rotation + 90) % 360
    },

    // 页面导航
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
      }
    },

    nextPage() {
      if (this.currentPage < this.numPages) {
        this.currentPage++
      }
    },

    goToPage(page) {
      const pageNum = parseInt(page)
      if (pageNum >= 1 && pageNum <= this.numPages) {
        this.currentPage = pageNum
      } else {
        this.$message.warning(`页码必须在 1 到 ${this.numPages} 之间`)
        this.currentPage = Math.min(Math.max(1, pageNum), this.numPages)
      }
    },

    // 下载PDF
    async downloadPDF() {
      try {
        const response = await fetch(this.url)
        const blob = await response.blob()
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = 'document.pdf'
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
      } catch (error) {
        console.error('下载失败:', error)
        this.$message.error('PDF下载失败')
      }
    },

    // 打印PDF
    printPDF() {
      const iframe = document.createElement('iframe')
      iframe.style.display = 'none'
      iframe.src = this.url
      document.body.appendChild(iframe)
      iframe.contentWindow.print()
      
      setTimeout(() => {
        document.body.removeChild(iframe)
      }, 1000)
    }
  },
  watch: {
    url: {
      handler(newUrl) {
        if (newUrl) {
          this.loadPDF()
        }
      },
      immediate: true
    }
  },
  beforeDestroy() {
    if (this.src && this.src.url && this.src.url.startsWith('blob:')) {
      URL.revokeObjectURL(this.src.url)
    }
  }
}
</script>

<style lang="scss" scoped>
.pdf-preview-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.pdf-toolbar {
  padding: 10px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;

  .el-button-group {
    margin-right: 10px;
    
    &:last-child {
      margin-right: 0;
    }
  }
}

.pdf-viewer {
  flex: 1;
  padding: 20px;
  background-color: #f0f2f5;
  overflow: auto;
  display: flex;
  justify-content: center;
  align-items: flex-start;

  .vue-pdf {
    background-color: white;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}

.page-info {
  display: inline-block;
  margin: 0 10px;
  color: #606266;
  line-height: 32px;
}

.empty-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;

  i {
    font-size: 48px;
    margin-bottom: 10px;
  }
}
</style> 